package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.dao;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;
import java.util.Map;

public class UserDao {
    private DatabaseReference databaseReference;

    public UserDao() {
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        databaseReference = database.getReference("users");
    }

    public void authenticateUser(String account, String password, String role, final OnAuthenticationListener listener) {
        databaseReference.orderByChild("account").equalTo(account).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean isAuthenticated = false;
                for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                    String userPassword = userSnapshot.child("password").getValue(String.class);
                    String userRole = userSnapshot.child("role").getValue(String.class);
                    if (password.equals(userPassword) && role.equals(userRole)) {
                        isAuthenticated = true;
                        break;
                    }
                }
                listener.onAuthenticationResult(isAuthenticated);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                listener.onAuthenticationResult(false);
            }
        });
    }

    //检查电话号码是否已经注册的逻辑
    public void checkPhoneNumber(String phoneNumber, final OnCheckPhoneNumberListener listener) {
        databaseReference.orderByChild("tel").equalTo(phoneNumber).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Log.d("UserDao", "检查手机号结果：" + dataSnapshot.exists());
                listener.onCheckResult(dataSnapshot.exists());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.e("UserDao", "检查手机号时发生错误：" + databaseError.getMessage());
                listener.onCheckResult(false);
            }
        });
    }

    public void saveUser(String account, String password, String phoneNumber, String role, final OnSaveUserListener listener) {
        String userId = databaseReference.push().getKey();
        Map<String, Object> user = new HashMap<>();
        user.put("account", account);
        user.put("password", password);
        user.put("tel", phoneNumber);
        user.put("role", role);

        if (userId != null) {
            databaseReference.child(userId).setValue(user)
                    .addOnSuccessListener(aVoid -> {
                        Log.d("UserDao", "保存用户信息成功");
                        listener.onSaveResult(true);
                    })
                    .addOnFailureListener(e -> {
                        Log.e("UserDao", "保存用户信息失败：" + e.getMessage());
                        listener.onSaveResult(false);
                    });
        } else {
            Log.e("UserDao", "生成用户 ID 失败");
            listener.onSaveResult(false);
        }
    }

    public interface OnAuthenticationListener {
        void onAuthenticationResult(boolean isAuthenticated);
    }

    public interface OnCheckPhoneNumberListener {
        void onCheckResult(boolean isRegistered);
    }

    public interface OnSaveUserListener {
        void onSaveResult(boolean isSaved);
    }
}